<?php
class Reviews_Model extends Model
{
	private $tableName;
	public function __construct()
	{
		parent::Model();
		$this->obj =& get_instance();
		$this->tableName = 'reviews';
	}
	
	public function getGameReviews($gameID)
	{
		$results = array();
		$sql = " SELECT  r.review_content, r.review_time, r.version, u.user_name
		FROM games g left join reviews r on (g.id=r.game_id)
		left join users u on (r.user_id = u.id)
		where 1
		and g.id ='$gameID'
		and r.id is not null
		and u.id is not null
		ORDER BY r.version DESC
		";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0) 
		{
			foreach ($query->result_array() as $row)      // Go through the result set
			{
				// Build up a list for each column from the database and place it in
				// ...the result set
				$query_results['review_content']	= $row['review_content'];
				$query_results['review_time']		= $row['review_time'];
				$query_results['version']	 		= $row['version'];
				$query_results['user_name']	 		= $row['user_name'];				
				$results[]		 = $query_results;
			}
		}
		return $results;
	}
	
	public function getLatestReview($gameID)
	{
		$result = array();
		
		$sql = "SELECT `id` , `review_content` , `review_time` , `version` , `game_id`
				FROM `reviews`
				WHERE 1 AND game_id = '$gameID'
				AND version = (	SELECT max( version ) FROM reviews WHERE 1	AND game_id = '$gameID'	GROUP BY game_id )
		 		LIMIT 0 , 1
		";
		$query = $this->db->query($sql);

		if ($query->num_rows() > 0) 	
		{
			$result = $query->row_array();
		}
		else
			$result = null;
		return $result;		
	}
	
	/*
	*	add
	*	@PARA: $data
	*	@RETURN: id
	*/
	function add( $data ) 
	{
		$data['version'] = $this->getNewVersionNum($data['game_id']);
		$data['review_time'] = date('Y-m-d h:i:s');
		// Load the database library
		$this->load->database();
		// Build up the SQL query string
		$sql = $this->db->insert_string($this->tableName, $data);
		$query = $this->db->query($sql);
		return $this->db->insert_id();
	}
	
	public function getNewVersionNum($gameID)
	{
		$newVersionNum = 0;
		
		$sql = "SELECT IFNULL( ( max( version ) +1 ) , 1) AS newVersionNum
		FROM `reviews`	WHERE 1	AND game_id = '$gameID' ";

		$query = $this->db->query($sql);

		if ($query->num_rows() > 0) 	
		{
			$row = $query->row_array();
			$newVersionNum = $row['newVersionNum'];
		}
		return $newVersionNum;
	}
}
?>